package com.ma.controller;

import com.ma.Utils.filesUtil;
import com.ma.entity.*;
import com.ma.server.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;


import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


/**
 * @ProjectName: project
 * @Package: com.ma.controller
 * @ClassName: teamCon
 * @Author: YHHHH
 * @Description:
 * @Date: 2021/3/3 14:21
 * @Version: 1.0
 */

@RestController
@CrossOrigin
public class teamCon {


    @Autowired
    private teamServer teamServer;
    @Autowired
    private LoginServer loginServer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StudentServer studentServer;
    @Autowired
    private MessageServe messageServe;
    @Autowired
    private FilesServer filesServer;
    @Autowired
    private filesUtil filesUtil;

    @Value("${upload.dir}")
    private  String realPath;         //文件存储位置

    @Value("${server.port}")
    private  String port;

    /*
    找到所有的小组
     */
    @GetMapping("/team/findAll")
    public List<Team> findAll(){
        List<Team> allTeam = teamServer.findAllTeam();
        return allTeam;
    }
    /*
    找到小组的详细信息
     */
    @GetMapping("/team/findMyTeam")
    public List<Map> findMyTeam(@RequestParam("number")String number){
        List<Map> resMap = new ArrayList<>();
        Map<String ,Object > map = new HashMap<>();
        Integer teamID = studentServer.findTeamID(number);              //找到小组的Id
        String leaderName = teamServer.findLeaderName(teamID);          //找到队长
        System.out.println(leaderName);
        List<Team> teamData = teamServer.findTeamData(teamID);
        map.put("team",teamData);
        map.put("leader",leaderName);
        resMap.add(map);

        return resMap;
    }
    /*
    找到学生的详细信息
     */
    @GetMapping("/login/findStudent")
    public Student findStudent(@RequestParam("number")String number){
      //  redisTemplate.setStringSerializer(new StringRedisSerializer());
        if(redisTemplate.hasKey(number)){
            Student oneStudent = (Student) redisTemplate.opsForValue().get(number);
            return oneStudent;
        }else {
            Student oneStudent = loginServer.findLoginStudent(number);
            System.out.println(oneStudent);
            redisTemplate.setStringSerializer(new StringRedisSerializer());
            redisTemplate.opsForValue().set(number,oneStudent);
            return oneStudent;
        }
    }

    /*
    登陆
     */
    @PostMapping("/login/loginText")
    public StudentVO loginText(@RequestBody StudentVO student){
        //String username = student.getUsername();
        StudentVO studentVO = loginServer.loginText(student.getNumber());
        System.out.println(studentVO);
        if (studentVO!=null){
            return studentVO;
        }else {
            return null;
        }
    }

    /*
    新建小组
     */
    @PostMapping("/team/addTeam")
    public String addTeam(@RequestBody Team team,HttpServletRequest request) {
      //  redisTemplate.setStringSerializer(new StringRedisSerializer());
        System.out.println(team);
        String token = request.getHeader("token");
        System.out.println(token);
        Integer addTeam = teamServer.addTeam(team);    //新增小组
        System.out.println(team.getTeamId());
        Integer state = 1;
//        Student loginStudent = loginServer.findLoginStudent(token);
//        Integer studentId = loginStudent.getStudentId();
        studentServer.updateStudentTeam(token,team.getTeamId(),state);  //改变学生的组号
        //将redis 里的数据改一下
        Student receiveStudent = loginServer.findLoginStudent(token);
        redisTemplate.opsForValue().set(token,receiveStudent);
        return "success";
    }


    /*
    发送入队审核消息
     */
    @GetMapping("/team/joinTeam")
    public String joinTeam(@RequestParam("teamId") Integer teamId, @RequestParam("number") String number){
       // redisTemplate.setStringSerializer(new StringRedisSerializer());
        Student student = (Student) redisTemplate.opsForValue().get(number);
        System.out.println(student);
        String studentName = student.getStudentName();
        String leader = teamServer.findLeader(teamId);     //找到队长学号
        System.out.println(leader);
        Message message = new Message();
        System.out.println(number);
        message.setSendId(number);
        message.setReceiveId(leader);
        message.setMessage("【审核消息】收到来自"+studentName+"(学号："+number+"）的入队申请，请及时审核！");
        Integer integer = messageServe.addMessage(message);

        return number;
    }

    /*
    审核通过加入小组
     */
    @PostMapping("/message/passJoinTeam")
    public String passJoinTeam(@RequestBody Message message){
     //   redisTemplate.setStringSerializer(new StringRedisSerializer());
        System.out.println(message);
        String joinNumber = message.getSendId();            //发送者的学号  也就是请求入队者
        String leaderNumber = message.getReceiveId();      //接受者，也就是队长
        // String joinNumber = message.substring(message.indexOf(":")+1, message.indexOf(")"));  //接收者的ID
        Integer teamID = studentServer.findTeamID(leaderNumber);
        System.out.println(teamID);
        Integer state = 0;
        Integer integer = studentServer.updateStudentTeam(joinNumber,teamID,state);   //修改学生的组号
        System.out.println("修改成功："+integer);
        if (integer==1){
            Message message1 = new Message();
            //将redis 里的数据改一下
            Student receiveStudent = loginServer.findLoginStudent(joinNumber);
            redisTemplate.opsForValue().set(joinNumber,receiveStudent);
            //发送加入成功的消息给请求者
            message1.setSendId(leaderNumber);
            message1.setReceiveId(joinNumber);
            message1.setMessage("您已经通过队长审核，成功加入小组！");
            Integer integer1 = messageServe.addMessage(message1);
            //修改消息为已读
            Integer state1 = messageServe.updateState(message.getId());
            return "success!";
        }else {
            return "fail!";
        }
    }
    /*
    审核确认退队
     */
    @PostMapping("/message/passExitTeam")
    @Transactional
    public String passExitTeam(@RequestBody Message message){
        System.out.println(message);
       // redisTemplate.setStringSerializer(new StringRedisSerializer());
        String exitNumber = message.getSendId();            //发送者的学号  也就是请求退队的人
        String leaderNumber = message.getReceiveId();       //接受者，也就是队长
        //把退队的人的teamId改为null
//        Integer teamID = studentServer.findTeamID(leaderNumber);
//        System.out.println(teamID);
        Integer state = 0;
        Integer integer = studentServer.updateStudentTeam(exitNumber,null,state);   //修改学生的组号
        System.out.println("修改成功："+integer);
        if (integer==1){
            Message message1 = new Message();
            //将redis 里的数据改一下
            Student receiveStudent = loginServer.findLoginStudent(exitNumber);
            redisTemplate.opsForValue().set(exitNumber,receiveStudent);
            //发送加入成功的消息给请求者
            message1.setSendId(leaderNumber);
            message1.setReceiveId(exitNumber);
            message1.setMessage("您已经通过队长审核，成功退出该小组！");
            Integer integer1 = messageServe.addMessage(message1);
            //修改消息为已读
            Integer state1 = messageServe.updateState(message.getId());
            //将文件从内存删除
            List<Files> byNumber = filesServer.findByNumber(exitNumber);
            for (Files files : byNumber) {
                Integer filesId = files.getFilesId();
                filesUtil.filesDelete(filesId);
            }
            Integer integer2 = filesServer.deleteStudentFiles(exitNumber);      //将文件从数据库删除
            return "success!";
        }else {
            return "fail!";
        }

    }
    /*
    改变头像
     */
    @PostMapping("/update/image")
    public String updateImage(@RequestBody  Map<String,String> map){
        //redisTemplate.setStringSerializer(new StringRedisSerializer());
        String url = map.get("url");
        String number = map.get("number");
        String rawBase64 = url.substring(url.indexOf(",") + 1);
        System.out.println(number);
        BASE64Decoder decoder = new BASE64Decoder();
        String newName = UUID.randomUUID().toString()+".jpg";        //文件新名字
        try {
            FileOutputStream fos = new FileOutputStream(new File(realPath,newName));
            byte[] imageByte = decoder.decodeBuffer(rawBase64);           //将Base64转化为字节编码
            fos.write(imageByte);
            fos.close();
            String newUrl = "http://localhost:"+port+"/"+newName;    //设置访问地址；
            Integer integer = studentServer.updateImage(number, newUrl);
            //将redis 里的数据改一下
            Student receiveStudent = loginServer.findLoginStudent(number);
            redisTemplate.opsForValue().set(number,receiveStudent);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    更改学生信息
     */
    @PostMapping("/update/updateData")
    public String updateData(@RequestBody Student student) {
        //redisTemplate.setStringSerializer(new StringRedisSerializer());
        System.out.println(student);
        String studentNumber = student.getStudentNumber();
        String studentPhone = student.getStudentPhone();
        String studentEmail = student.getStudentEmail();
        Integer integer = studentServer.updateData(studentNumber, studentPhone, studentEmail);
        if ((integer != 0)) {
            //将redis 里的数据改一下
            Student receiveStudent = loginServer.findLoginStudent(studentNumber);
            redisTemplate.opsForValue().set(studentNumber,receiveStudent);
            return "success!";
        } else {
            return "fail!";
        }
    }
    /*
    转化队长
     */
    @GetMapping("/team/changeLeader")
    public String  turnLeader(@RequestParam("number")String  number,@RequestParam("name")String name,@RequestParam("OldName")String oldNumber){
        System.out.println(number);
        System.out.println(name);
        System.out.println(oldNumber);
        String studentName = loginServer.findOneStudentName(number);
        System.out.println(studentName);
        if (studentName!=null&&studentName.equals(name)){
            Integer oldLeader = studentServer.updateNoLeader(oldNumber);
            Integer newLeader = studentServer.updateLeader(number);
            if (newLeader==0||oldLeader==0){
                return "更改失败请稍后再试";
            }else {
                return "success";
            }
        }else {
            return "姓名与学号不匹配！";
        }
    }

    /*
    找到所有组员
     */
    @GetMapping("/team/findAllTeammate")
    public List<String> findAllTeammate(@RequestParam("teamId")Integer teamId){
        System.out.println(teamId);
        List<String> allTeammate = studentServer.findAllTeammate(teamId);
        return allTeammate;
    }



}
